package com.example.petstore.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.petstore.common.CommonResponse;
import com.example.petstore.domain.*;
import com.example.petstore.mapper.*;
import com.example.petstore.util.ZFBqrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("orderService")
@Slf4j
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private SequenceMapper sequenceMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private CartItemMapper cartItemMapper;
    @Autowired
    private LineItemMapper lineItemMapper;

    public CommonResponse userBuyItemAtOnce(String username, String itemId, int number) {
//        调整库存
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("itemid", itemId);
        List<Item> items = itemMapper.selectList(queryWrapper);
        Item item;
        if(items.size() > 0){
            item = items.get(0);
            if(item.getQty() - number >= 0) {
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("itemid", itemId);
                if (item.getQty() - number < 0) {
                    return CommonResponse.creatForError("库存不足");
                }
                updateWrapper.set("qty", item.getQty() - number);
                int result = itemMapper.update(updateWrapper);
                if (result != 1) {
                    return CommonResponse.creatForError("出错了，请稍后再试。");
                }
            }
        }else {
            return CommonResponse.creatForError("出错了，请稍后再试。");
        }

        Order order = new Order();
        OrderInit(order, username);

        LineItem lineItem = new LineItem();
        lineItem.setItemid(itemId);
        lineItem.setOrderid(order.getOrderid());
        lineItem.setLineNum(1);
        lineItem.setQuantity(number);

        lineItem.setUnitprice(item.getListprice());
        order.setTotalprice(countTotalPrice(lineItem));
        lineItemMapper.insert(lineItem);

        orderMapper.insert(order);
        return CommonResponse.creatForSuccess(order);
    }

    private double countTotalPrice(LineItem lineItem) {
        return lineItem.getQuantity() * lineItem.getUnitprice();
    }

    /*将username的购物车中物品放入lineItem*/
    public CommonResponse userBuyCartItem(String username){
        Order order = new Order();
        OrderInit(order, username);

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        List<CartItem> cartItemList = cartItemMapper.selectList(queryWrapper);
        int orderid = order.getOrderid();
        for(CartItem cartItem : cartItemList){
            queryWrapper = new QueryWrapper();
            queryWrapper.eq("itemid", cartItem.getItemid());
            Item item = itemMapper.selectOne(queryWrapper);
            if(item == null){
                return CommonResponse.creatForError("出错了，请稍后再试");
            }else{
                if(item.getQty() < cartItem.getQuantity()){
                    return CommonResponse.creatForError(cartItem.getItemid() + "库存不足");
                }
            }
        }

        double total = 0;
        int i = 1;
        for(CartItem cartItem : cartItemList){
            LineItem lineItem = new LineItem();
            lineItem.setOrderid(orderid);
            lineItem.setLineNum(i);
            i++;
            lineItem.setItemid(cartItem.getItemid());
            lineItem.setQuantity(cartItem.getQuantity());
//            找到原来库存
            QueryWrapper queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("itemid", cartItem.getItemid());
            Item item = itemMapper.selectOne(queryWrapper2);
//            更新库存
            UpdateWrapper updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("itemid", cartItem.getItemid());
            updateWrapper.set("qty", item.getQty() - cartItem.getQuantity());
            itemMapper.update(updateWrapper);

            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("itemid", cartItem.getItemid());
            Item item1 = itemMapper.selectOne(queryWrapper1);
            lineItem.setUnitprice(item1.getListprice());

            total += item1.getListprice() * lineItem.getQuantity();
            lineItemMapper.insert(lineItem);
        }
        order.setTotalprice(total);
//        System.out.println("orderservice:" + order);
        orderMapper.insert(order);
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("username", username);
        cartItemMapper.delete(queryWrapper1);/*不确定是否生效*/
        return CommonResponse.creatForSuccess(order);
    }

    private void OrderInit(Order order, String username) {

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        QueryWrapper seqw = new QueryWrapper<>();
        seqw.eq("name", "ordernum");
        Sequence sequence = sequenceMapper.selectOne(seqw);

        order.setOrderid(sequence.getNextid());

        UpdateWrapper updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("name", "ordernum");
        updateWrapper.set("nextid", sequence.getNextid() + 1);
        sequenceMapper.update(updateWrapper);

        order.setUsername(username);
        order.setOrderDate(LocalDateTime.now().toLocalDate());
        order.setShipaddr1(userInfo.getAddr1()==null ? "" : userInfo.getAddr1());
        order.setShipaddr2(userInfo.getAddr2()==null ? "" : userInfo.getAddr2());
        order.setShipcity(userInfo.getCity()==null ? "" : userInfo.getCity());
        order.setShipstate(userInfo.getState()==null ? "" : userInfo.getState());
        order.setShipzip(userInfo.getZip()==null ? "" : userInfo.getZip());
        order.setShipcountry(userInfo.getCountry()==null ? "" : userInfo.getCountry());
        order.setBilladdr1(userInfo.getAddr1()==null ? "" : userInfo.getAddr1());
        order.setBilladdr2(userInfo.getAddr2()==null ? "" : userInfo.getAddr2());
        order.setBillcity(userInfo.getCity()==null ? "" : userInfo.getCity());
        order.setBillstate(userInfo.getState()==null ? "" : userInfo.getState());
        order.setBillzip(userInfo.getZip()==null ? "" : userInfo.getZip());
        order.setBillcountry(userInfo.getCountry()==null ? "" : userInfo.getCountry());
        order.setBilltofirstname(userInfo.getFirstname()==null ? "" : userInfo.getFirstname());
        order.setBilltolastname(userInfo.getLastname()==null ? "" : userInfo.getLastname());
        order.setShiptofirstname(userInfo.getFirstname()==null ? "" : userInfo.getFirstname());
        order.setShiptolastname(userInfo.getLastname()==null ? "" : userInfo.getLastname());
        order.setCreditcard("999 9999 9999 9999");
        order.setCardtype("Visa");
        order.setLocale("CA");
        order.setIspay(false);
        order.setIssend(false);
        order.setSendnumber(null);
        order.setIsget(false);
        order.setIsreturn(false);
        order.setExprdate("12/3");
        order.setOutTradeNo("");
    }

    public CommonResponse userFindNoShipOrder(String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        queryWrapper.eq("issend", 0);
        List<Order> orderLine = orderMapper.selectList(queryWrapper);
        return CommonResponse.creatForSuccess(orderLine);
    }

    public CommonResponse getUserOrderList(String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        return CommonResponse.creatForSuccess(orders);
    }

    public CommonResponse<List<Order>> userFindShipOrder(String username) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("issend", 1);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        return CommonResponse.creatForSuccess(orders);
    }

    public CommonResponse<List<Order>> userFindNoPayOrder(String username) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("ispay", 0);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        return CommonResponse.creatForSuccess(orders);
    }

    public CommonResponse getQRCode(Order order) {
        try{
            Map map = ZFBqrUtil.getQR(order.getTotalprice());
//            todo:???
            String qr = (String)map.get("qrcode");
            return CommonResponse.creatForSuccess(qr);
        }catch (Exception e){
            e.printStackTrace();
            return CommonResponse.creatForError("二维码获取失败");
        }
    }

    /*
    * 用户删除/取消未支付订单 test ok
    * */
    public CommonResponse userDeleteOrder(int orderId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderid", orderId);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        if(orders.size() > 0){
            Order order = orders.get(0);
            boolean ispay = order.isIspay();
            if(ispay){
                log.warn("orderId " + order + " 订单已经付款无法取消");
                return CommonResponse.creatForError("订单已经付款无法取消");
            }

            List<LineItem> lineItems = lineItemMapper.selectList(queryWrapper);
            UpdateWrapper updateWrapper;
            QueryWrapper queryWrapper1;
            for(LineItem lineItem : lineItems){
                queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("itemid", lineItem.getItemid());
                Item item = itemMapper.selectOne(queryWrapper1);

                updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("itemid", lineItem.getItemid());
                updateWrapper.set("qty", item.getQty() + lineItem.getQuantity());
                itemMapper.update(updateWrapper);
            }
//            lineItemMapper.delete(queryWrapper);

            updateWrapper = new UpdateWrapper();
            updateWrapper.eq("orderid", orderId);
            updateWrapper.set("iscancel", 1);
            orderMapper.update(updateWrapper);
            log.info("orderId " + order + " 取消成功");
            return CommonResponse.creatForSuccessMessage("取消成功");
        }
        return CommonResponse.creatForError("出错了，请稍后再试");
    }

    /**
     * 退货
     * @param orderId
     * @return
     */
    public CommonResponse userReturnOrder(int orderId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderid", orderId);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        if(orders.size() > 0){
            Order order = orders.get(0);
            boolean ispay = order.isIspay();
            if(!ispay){
                log.warn("orderId " + order + " 订单未付款无法退货");
                return CommonResponse.creatForError("订单未付款无法退货");
            }

            List<LineItem> lineItems = lineItemMapper.selectList(queryWrapper);
            UpdateWrapper updateWrapper;
            QueryWrapper queryWrapper1;
            for(LineItem lineItem : lineItems){
                queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("itemid", lineItem.getItemid());
                Item item = itemMapper.selectOne(queryWrapper1);

                updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("itemid", lineItem.getItemid());
                updateWrapper.set("qty", item.getQty() + lineItem.getQuantity());
                itemMapper.update(updateWrapper);
            }
//            lineItemMapper.delete(queryWrapper);

            updateWrapper = new UpdateWrapper();
            updateWrapper.eq("orderid", orderId);
            updateWrapper.set("isreturn", 1);
            orderMapper.update(updateWrapper);

            try {
                ZFBqrUtil.returnMoney(order.getOutTradeNo(), order.getTotalprice());
            }catch (Exception e){
                log.info("orderId " + orderId + " 退款失败");
                return CommonResponse.creatForSuccessMessage("退货成功");
            }

            log.info("orderId " + orderId + " 退货成功");
            return CommonResponse.creatForSuccessMessage("退货成功");
        }
        return CommonResponse.creatForError("出错了，请稍后再试");
    }

    public CommonResponse getOrderByOrderId(String orderId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderid", orderId);
        Order order = orderMapper.selectOne(queryWrapper);
        log.info("获取 orderId " + order + " 详情");
        return CommonResponse.creatForSuccess(order);
    }

    public boolean finishPay(int orderId) {
        UpdateWrapper updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("orderid", orderId);
        updateWrapper.set("ispay", 1);
        int result = orderMapper.update(updateWrapper);
        if(result == 1){
            log.info("orderId " + orderId + " 付款成功");
            return true;
        }else{
            log.info("orderId " + orderId + " 付款失败");
            return false;
        }
    }

    public boolean cancelPay(int orderId) {
        UpdateWrapper updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("orderid", orderId);
        updateWrapper.set("iscancel", 1);
        int result = orderMapper.update(updateWrapper);
        if(result == 1){
            log.info("orderId " + orderId + " 取消成功");
            return true;
        }else{
            log.info("orderId " + orderId + " 取消失败");
            return false;
        }
    }

    public CommonResponse userFindAllOrder(String username) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        log.info("用户获取全部订单");
        return CommonResponse.creatForSuccess(orders);
    }

    public CommonResponse userFindNoGetOrder(String username) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("isget", 0);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        log.info("用户获取未收货订单");
        return CommonResponse.creatForSuccess(orders);
    }

    public void updateOrderByOrderId(Order order) {
        UpdateWrapper updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("orderid", order.getOrderid());
        orderMapper.update(order, updateWrapper);
    }

    public void updateOutTradeNoByOrderId(String outTradeNo, int orderid) {
        UpdateWrapper updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("orderid", orderid);
        updateWrapper.set("outtradeno", outTradeNo);


        int res = orderMapper.update(updateWrapper);
        System.out.println("res = " + res);
    }
}

